package com.example.excel_upload.excel.service.impl;

import com.example.excel_upload.excel.service.ExcelService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

@Service
public class ExcelServiceImpl implements ExcelService {
    @Override
    public void readExcel(MultipartFile excel) throws IOException {

        //创建临时文件存储excel
        File tempFile = File.createTempFile( "./1", "xlsx");
        excel.transferTo(tempFile);

        //将临时文件转为XSSFWorkbook格式
        InputStream fileInput = new FileInputStream(tempFile);
        XSSFWorkbook workbook = new XSSFWorkbook(fileInput);
        int sheetIndex = 0;

        //循环excel文件中的每一个sheet
        for(XSSFSheet sheet; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
            sheet = workbook.getSheetAt(sheetIndex);

            //读取sheet表中的每一行
            for (Row row : sheet) {

                //输出每一行的第一列数据
                System.out.println(row.getCell(0));
            }
        }

        //删除临时文件
        tempFile.delete();
        fileInput.close();
    }
}
